import express from "express";
import fs from "fs";
import jsYaml from "js-yaml";
import Result from "../utils/Result.js";
import path from "path";
import crypto from "node:crypto"
import knex from "knex";

const router = express.Router();
// 读取配置文件
const configPath = path.resolve(process.cwd(), "./db.config.yaml");
const yaml = fs.readFileSync(configPath, "utf8");
// 加载配置文件
const config = jsYaml.load(yaml);
// 创建knex链接
const db = knex({
  client: 'mysql2',
  connection: config.db
})


// 添加用户
router.post("/addUser", async (req, res) => {
  let { user_name, password, email, phone } = req.body;

  // 查询用户名是否已存在
  const rows = await db('user').count("* as count").where({
    user_name: user_name
  });
  if (rows[0].count > 0) {
    res.json(Result.error("用户名已存在"));
    return;
  }
  // 如果用户不存在，则添加用户，并且返回新增的用户ID
  // 对密码进行md5加密
  password = crypto.createHash('md5').update(password).digest('hex')
  // 获取当前时间
  let create_time = new Date()

  // 执行插入方法
  const [id] = await db('user').insert({
    user_name: user_name,
    password: password,
    email: email,
    phone: phone,
    create_time: create_time
  })

  res.json(Result.success(id));
});

// 删除用户
router.post("/deleteUser", async (req, res) => {
  let { id } = req.query;
  // 执行删除方法
  await db("user").delete().where({
    id: id
  })
  res.json(Result.success());
})

// 查询指定id信息
router.get("/getUserById", async (req, res) => {
  let { id } = req.query;
  const data = await db("user")
    .select("id", "user_name", "phone", "email", "create_time")
    .where({
      id: id
    })
  res.json(Result.success(data[0]));
})

// 根据id修改用户
router.post("/updateUser", async (req, res) => {
  let { id, user_name, email, phone } = req.body;
  // 执行修改方法
  const data = await db("user")
    .update({
      user_name: user_name,
      email: email,
      phone: phone
    })
    .where({
      id: id
    })
  res.json(Result.success(data))
})

// 查询所有用户
router.get("/getAllUsers", async (req, res) => {
  let user_name = req.query.user_name;

  const data = await db("user")
    .select()
    .where('user_name', 'like', `%${user_name}%`)
  res.json(Result.success(data));
});


export default router;
